"""
AI Agent Pro - 智能体管理 API
"""

import uuid
from typing import Dict, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import StreamingResponse
from slowapi import Limiter
from slowapi.util import get_remote_address

from app.core.exceptions import AgentNotFoundError, AgentCreationError
from app.core.logging import get_logger, log_agent_action
from app.models.agent import Agent, AgentCreate, AgentUpdate, AgentResponse
from app.services.agent_service import AgentService
from app.api.dependencies import get_current_user, get_agent_service

logger = get_logger(__name__)
router = APIRouter()

# 限流器
limiter = Limiter(key_func=get_remote_address)


@router.post("/", response_model=AgentResponse, status_code=status.HTTP_201_CREATED)
@limiter.limit("10/minute")
async def create_agent(
    agent_data: AgentCreate,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    创建新的智能体
    
    - **name**: 智能体名称
    - **description**: 智能体描述
    - **model**: 使用的AI模型
    - **tools**: 可用工具列表
    - **config**: 智能体配置
    """
    try:
        agent = await agent_service.create_agent(
            user_id=current_user["id"],
            agent_data=agent_data
        )
        
        log_agent_action(
            agent_id=agent.id,
            action="CREATE",
            user_id=current_user["id"],
            model=agent.model
        )
        
        logger.info(f"用户 {current_user['id']} 创建智能体 {agent.id}")
        
        return agent
        
    except Exception as e:
        logger.error(f"创建智能体失败: {str(e)}")
        raise AgentCreationError(str(e))


@router.get("/", response_model=List[AgentResponse])
async def list_agents(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(20, ge=1, le=100, description="返回的记录数"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    model: Optional[str] = Query(None, description="过滤模型"),
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    获取智能体列表
    
    支持分页、搜索和过滤功能
    """
    agents = await agent_service.list_agents(
        user_id=current_user["id"],
        skip=skip,
        limit=limit,
        search=search,
        model_filter=model
    )
    
    return agents


@router.get("/{agent_id}", response_model=AgentResponse)
async def get_agent(
    agent_id: str,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    获取特定智能体的详细信息
    """
    agent = await agent_service.get_agent(
        agent_id=agent_id,
        user_id=current_user["id"]
    )
    
    if not agent:
        raise AgentNotFoundError(agent_id)
    
    return agent


@router.put("/{agent_id}", response_model=AgentResponse)
async def update_agent(
    agent_id: str,
    agent_data: AgentUpdate,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    更新智能体配置
    """
    agent = await agent_service.update_agent(
        agent_id=agent_id,
        user_id=current_user["id"],
        agent_data=agent_data
    )
    
    if not agent:
        raise AgentNotFoundError(agent_id)
    
    log_agent_action(
        agent_id=agent_id,
        action="UPDATE",
        user_id=current_user["id"],
        changes=agent_data.dict(exclude_unset=True)
    )
    
    logger.info(f"用户 {current_user['id']} 更新智能体 {agent_id}")
    
    return agent


@router.delete("/{agent_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_agent(
    agent_id: str,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    删除智能体
    """
    success = await agent_service.delete_agent(
        agent_id=agent_id,
        user_id=current_user["id"]
    )
    
    if not success:
        raise AgentNotFoundError(agent_id)
    
    log_agent_action(
        agent_id=agent_id,
        action="DELETE",
        user_id=current_user["id"]
    )
    
    logger.info(f"用户 {current_user['id']} 删除智能体 {agent_id}")


@router.post("/{agent_id}/clone", response_model=AgentResponse)
async def clone_agent(
    agent_id: str,
    name: Optional[str] = None,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    克隆智能体
    """
    cloned_agent = await agent_service.clone_agent(
        agent_id=agent_id,
        user_id=current_user["id"],
        new_name=name
    )
    
    if not cloned_agent:
        raise AgentNotFoundError(agent_id)
    
    log_agent_action(
        agent_id=cloned_agent.id,
        action="CLONE",
        user_id=current_user["id"],
        source_agent_id=agent_id
    )
    
    logger.info(f"用户 {current_user['id']} 克隆智能体 {agent_id} -> {cloned_agent.id}")
    
    return cloned_agent


@router.get("/{agent_id}/stats")
async def get_agent_stats(
    agent_id: str,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    获取智能体统计信息
    """
    stats = await agent_service.get_agent_stats(
        agent_id=agent_id,
        user_id=current_user["id"]
    )
    
    if not stats:
        raise AgentNotFoundError(agent_id)
    
    return stats


@router.post("/{agent_id}/activate")
async def activate_agent(
    agent_id: str,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    激活智能体
    """
    success = await agent_service.activate_agent(
        agent_id=agent_id,
        user_id=current_user["id"]
    )
    
    if not success:
        raise AgentNotFoundError(agent_id)
    
    log_agent_action(
        agent_id=agent_id,
        action="ACTIVATE",
        user_id=current_user["id"]
    )
    
    return {"message": "智能体已激活", "agent_id": agent_id}


@router.post("/{agent_id}/deactivate")
async def deactivate_agent(
    agent_id: str,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    停用智能体
    """
    success = await agent_service.deactivate_agent(
        agent_id=agent_id,
        user_id=current_user["id"]
    )
    
    if not success:
        raise AgentNotFoundError(agent_id)
    
    log_agent_action(
        agent_id=agent_id,
        action="DEACTIVATE",
        user_id=current_user["id"]
    )
    
    return {"message": "智能体已停用", "agent_id": agent_id}


@router.get("/{agent_id}/conversations")
async def get_agent_conversations(
    agent_id: str,
    skip: int = Query(0, ge=0),
    limit: int = Query(20, ge=1, le=100),
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    获取智能体的对话历史
    """
    conversations = await agent_service.get_agent_conversations(
        agent_id=agent_id,
        user_id=current_user["id"],
        skip=skip,
        limit=limit
    )
    
    if conversations is None:
        raise AgentNotFoundError(agent_id)
    
    return conversations


@router.post("/{agent_id}/export")
async def export_agent(
    agent_id: str,
    format: str = Query("json", regex="^(json|yaml)$"),
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    导出智能体配置
    """
    export_data = await agent_service.export_agent(
        agent_id=agent_id,
        user_id=current_user["id"],
        format=format
    )
    
    if not export_data:
        raise AgentNotFoundError(agent_id)
    
    log_agent_action(
        agent_id=agent_id,
        action="EXPORT",
        user_id=current_user["id"],
        format=format
    )
    
    # 设置文件名
    filename = f"agent_{agent_id}.{format}"
    media_type = "application/json" if format == "json" else "application/x-yaml"
    
    return StreamingResponse(
        iter([export_data]),
        media_type=media_type,
        headers={"Content-Disposition": f"attachment; filename={filename}"}
    )


@router.post("/import")
async def import_agent(
    import_data: dict,
    current_user: dict = Depends(get_current_user),
    agent_service: AgentService = Depends(get_agent_service)
):
    """
    导入智能体配置
    """
    try:
        agent = await agent_service.import_agent(
            user_id=current_user["id"],
            import_data=import_data
        )
        
        log_agent_action(
            agent_id=agent.id,
            action="IMPORT",
            user_id=current_user["id"]
        )
        
        logger.info(f"用户 {current_user['id']} 导入智能体 {agent.id}")
        
        return agent
        
    except Exception as e:
        logger.error(f"导入智能体失败: {str(e)}")
        raise AgentCreationError(f"导入失败: {str(e)}")


@router.get("/models/available")
async def get_available_models():
    """
    获取可用的AI模型列表
    """
    # 这里应该从配置或服务中获取可用模型
    models = [
        {
            "id": "gpt-4",
            "name": "GPT-4",
            "provider": "OpenAI",
            "description": "最强大的语言模型",
            "capabilities": ["text", "reasoning", "code"],
            "context_length": 8192
        },
        {
            "id": "gpt-3.5-turbo",
            "name": "GPT-3.5 Turbo",
            "provider": "OpenAI",
            "description": "快速且经济的语言模型",
            "capabilities": ["text", "reasoning"],
            "context_length": 4096
        },
        {
            "id": "claude-3-opus",
            "name": "Claude 3 Opus",
            "provider": "Anthropic",
            "description": "Anthropic最强大的模型",
            "capabilities": ["text", "reasoning", "analysis"],
            "context_length": 200000
        },
        {
            "id": "claude-3-sonnet",
            "name": "Claude 3 Sonnet",
            "provider": "Anthropic",
            "description": "平衡性能和成本",
            "capabilities": ["text", "reasoning"],
            "context_length": 200000
        }
    ]
    
    return {"models": models}


@router.get("/templates")
async def get_agent_templates():
    """
    获取智能体模板
    """
    templates = [
        {
            "id": "coding_assistant",
            "name": "编程助手",
            "description": "专业的代码编写和调试助手",
            "model": "gpt-4",
            "tools": ["code_executor", "file_manager", "search"],
            "config": {
                "temperature": 0.1,
                "max_tokens": 2000,
                "system_prompt": "你是一个专业的编程助手..."
            }
        },
        {
            "id": "research_assistant",
            "name": "研究助手",
            "description": "帮助进行信息收集和分析",
            "model": "claude-3-sonnet",
            "tools": ["web_search", "document_analyzer", "summarizer"],
            "config": {
                "temperature": 0.3,
                "max_tokens": 3000,
                "system_prompt": "你是一个专业的研究助手..."
            }
        },
        {
            "id": "creative_writer",
            "name": "创意写作助手",
            "description": "协助创意写作和内容创作",
            "model": "gpt-4",
            "tools": ["text_analyzer", "style_checker"],
            "config": {
                "temperature": 0.7,
                "max_tokens": 4000,
                "system_prompt": "你是一个富有创意的写作助手..."
            }
        }
    ]
    
    return {"templates": templates}